﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls ;
using System.Web.UI.WebControls;
using System.Data;
using CVSA.Suporte.Sinacor.BMFBovespa.ConsultaRemedy.Common;
using CVSA.Suporte.Sinacor.BMFBovespa.Negocio;
using System.IO;

namespace CVSA.Suporte.Sinacor.BMFBovespa.ConsultaRemedy
{
    public partial class ListaChamadosRemedy : System.Web.UI.Page
    {
        private AppCache appCache = new AppCache();
        private DataView odvChamados = new DataView();
        private Remedy remedy = new Remedy();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                ltUltimaAtualizacao.Text = remedy.ultimoSincronismo().ToString();//.AddHours(1).ToString();
                chkAreasChamado.DataSource = appCache.Tb_AreasChamado();
                chkAreasChamado.DataTextField = "Area_Designada";
                chkAreasChamado.DataValueField = "Area_Designada";
                chkAreasChamado.DataBind();

                foreach (ListItem lst in chkAreasChamado.Items)
                {
                    //if (lst.Text == "DO-CSSE SUPORTE SINACOR - ANALISE" || lst.Text == "DO-CSSE SUPORTE SINACOR - PRE-ANALISE")
                    //{
                    lst.Selected = true;
                    //}
                }
                if (!String.IsNullOrEmpty(Request.QueryString["IdIncidente"]))
                {

                    txtIdIncidente.Text = Request.QueryString["IdIncidente"];
                }
                if (!String.IsNullOrEmpty(Request.QueryString["Pessoa"]))
                {

                    txtPessoa.Text = Request.QueryString["Pessoa"];
                }

                btnPesquisar_Click(null, null);

            }
        }

        protected void btnPesquisar_Click(object sender, EventArgs e)
        {
            try
            {
                //ltUltimaAtualizacao.Text = remedy.ultimoSincronismo().AddHours(1).ToString();

                if (rdTpPesquisaChamados.SelectedValue == "0")
                {
                    odvChamados.Table = appCache.Tb_ChamadosAbertos();
                }


                string filter = string.Empty;
                filter = "Area_Designada <> 'DO-CVSA-DEMANDAS' ";

                if (!String.IsNullOrEmpty(txtPessoa.Text))
                {
                    filter += " AND Pessoa_Designada like  '%" + txtPessoa.Text + "%'";
                }

                filter += " AND Empresa Like '%" + txtNomeCorretora.Text.ToUpper() + "%'";
                if (!String.IsNullOrEmpty(txtIdIncidente.Text))
                {
                    filter += " And IdIncidente Like '%" + txtIdIncidente.Text + "%'";
                }

                string filterPrioridade = string.Empty;

                int i = 0;
                foreach (ListItem lst in chkLstPrioridade.Items)
                {
                    if (lst.Selected)
                    {
                        if (i == 0)
                        {
                            filterPrioridade += " AND (";
                            filterPrioridade += " PRIORIDADE = '" + lst.Value + "'";
                        }
                        else
                        {
                            filterPrioridade += " OR PRIORIDADE = '" + lst.Value + "'";
                        }
                        i++;
                    }
                }

                if (filterPrioridade != string.Empty)
                {
                    filterPrioridade += " )";
                    filter += filterPrioridade;
                }

                i = 0;

                string filterArea = string.Empty;


                foreach (ListItem lst in chkAreasChamado.Items)
                {
                    if (lst.Selected)
                    {
                        if (i == 0)
                        {
                            filterArea += " AND (";
                            filterArea += " AREA_DESIGNADA= '" + lst.Value + "'";
                        }
                        else
                        {
                            filterArea += " OR AREA_DESIGNADA = '" + lst.Value + "'";
                        }
                        i++;
                    }
                }

                if (filterArea != string.Empty)
                {
                    filterArea += " )";
                    filter += filterArea;
                }

                if (rdTpPesquisaChamados.SelectedValue == "1")
                {

                    if (txtNomeCorretora.Text.Length >= 3 || txtIdIncidente.Text.Length >= 6)
                    {
                        odvChamados.Table = appCache.Tb_Chamados(" WHERE " + filter);
                    }
                }
                else
                {
                    odvChamados.RowFilter = filter;
                }

                gvChamadosRemedy.DataSource = odvChamados;
                gvChamadosRemedy.DataBind();
                ltlQtdChamados.Text = odvChamados.Count.ToString();
            }
            catch { }


        }

        public string FormatarTexto(string texto)
        {
            texto = texto.Replace("\n", "<br />");
            return texto;
        }

        protected void formatRow(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {

                DataRowView row = (DataRowView)e.Row.DataItem;
                HtmlAnchor href = (HtmlAnchor)e.Row.FindControl("showDetail");
                HtmlGenericControl div = (HtmlGenericControl)e.Row.FindControl("div_txt");

                if (row["Area_Designada"].Equals("DO-CSSA SUPORTE SINACOR - NEGOCIO"))
                {
                    e.Row.Style.Add("background-color", "#990000");
                    e.Row.Style.Add("color", "#FFFFFF");
                    href.Style.Add("color", "#FFFFFF");
                }

                if (row["Status"].Equals("InProgress"))
                {
                    e.Row.Style.Add("background-color", "#004080");
                    e.Row.Style.Add("color", "#FFFFFF");
                }

                if (row["Prioridade"].Equals("Critical"))
                {
                    e.Row.Style.Add("background-color", "#FFFFFF");
                    e.Row.Style.Add("color", "#990000");
                    e.Row.Style.Add("font-weight", "bold");
                }

                if (row["Status"].Equals("Closed") || row["Status"].Equals("Resolved") || row["Status"].Equals("Cancelled"))
                {
                    e.Row.Style.Add("background-color", "Teal");
                    e.Row.Style.Add("color", "#FFFFFF");
                }


                href.Attributes.Add("onclick", "javascript:showDetail(" + div.ClientID + ")");
                href.HRef = "#" + href.ClientID;

            }
        }

        protected void ExcelExport_Click(object sender, ImageClickEventArgs e)
        {
            PrepareGridViewForExport(gvChamadosRemedy);
            ExportGridView();
        }

        private void ExportGridView()
        {
            string attachment = "attachment; filename=Incidentes.xls";
            Response.ClearContent();
            Response.Charset = "ISO-8859-1";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("iso-8859-1"); 
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvChamadosRemedy.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
        }

        private void PrepareGridViewForExport(Control gv)
        {
            LinkButton lb = new LinkButton();
            Literal l = new Literal();
            string name = String.Empty;
            for (int i = 0; i < gv.Controls.Count; i++)
            {
                if (gv.Controls[i].GetType() == typeof(LinkButton))
                {
                    l.Text = (gv.Controls[i] as LinkButton).Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                else if (gv.Controls[i].GetType() == typeof(DropDownList))
                {
                    l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                else if (gv.Controls[i].GetType() == typeof(CheckBox))
                {
                    l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                else if (gv.Controls[i].GetType() == typeof(HtmlImage))
                {
                    gv.Controls.Remove(gv.Controls[i]);
                    gv.Controls.AddAt(i, l);
                }

                if (gv.Controls[i].HasControls())
                {
                    PrepareGridViewForExport(gv.Controls[i]);
                }
            }
        }
    }
}
